package com.leyou.cart.filter;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.cart.config.JwtProperties;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器，定义之后仍需要配置到SpringMVC拦截器
 * Created by 冯金平 on 2023/3/23 10:26
 * 登录拦截校验
 *
 * @author Administrator
 * @date 2023/03/23
 */
//标记本类使用配置Bean
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtProperties properties;
    //本地存放的登录用户信息，TL线程本地共享因此Controller 也可以访问
    private static final ThreadLocal<UserInfo> tl = new ThreadLocal<>();

    public LoginInterceptor(JwtProperties properties) {
        this.properties = properties;
    }

    /**
     * 拦截处理
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        登录判断
        String token = CookieUtils.getCookieValue(request, this.properties.getCookiename());
        if (StringUtils.isNotBlank(token)){
//        已经登录存入本地
            //解析token中的用户信息
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.properties.getPublicKey());
            tl.set(userInfo);
            return true;
        }
//        未登录拦截
        //响应给客户端,未授权
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;

    }

    /**
     * 下单完成后删除
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @param ex       前女友
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空Tomcat线程池，不会结束，这个线程不结束变量也不会被回收到达数量将报错
        tl.remove();
    }
//    controll调用
    public static UserInfo getLoginUser() {
        return tl.get();
    }
}
